<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends BaseController {

	public function __construct() {
        parent::__construct();
    }

	public function index() {
        $this->load->model('schoolModel');
        // 学校数据
        $schoolData = array();
        $params['isDelete'] = 0;
        // 获取全部学校区域数据
        $schoolList = $this->schoolModel->get_school_list($params);
        foreach($schoolList as $school) {
            $province[$school['school_province']]['city'][$school['school_city']]['school'][] = array(
                "id" => $school['id'],
                "name" => $school['school_name']
            );
            $schoolData = $province;
        }
        // 获取城市名称
        foreach($schoolData as $pk => &$city) {
            // 获取省份信息
            $provinceInfo = $this->schoolModel->get_area_info($pk);
            $schoolData[$pk]['areaName'] = $provinceInfo['area_name'];
            // 获取市级信息
            foreach($city['city'] as $ck => $school) {
                $cityInfo = $this->schoolModel->get_area_info($ck);
                $city['city'][$ck]['areaName'] = $cityInfo['area_name'];
            }
        }

        $this->schoolData = json_encode($schoolData);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "login");
    }

    // 提交方法
    public function login_action(){
        $this->load->model('accountModel');
        $this->load->model('schoolModel');
        $this->load->model('staffModel');
        $this->load->model('classesModel');

        // 接收参数
        $schoolId = $this->post("school");
        $username = $this->post("username");
        $password = $this->post("password");
        $captcha = $this->post("captcha");
        // 参数检查
        if($captcha != $this->session->captcha) throw new Exception("请填写正确的验证码");
        // 查询数据库
        $userInfo = $this->accountModel->admin_login($username, $password);
        // 校区信息
        $campusInfo = $campusList = array();
        if(!$userInfo) {
            // 存在两个同账号用户，优先管理员
            $userInfo = $this->accountModel->school_user_login_only_admin($schoolId, $username, $password);
            if(empty($userInfo)) {
                // 检查老师登录
                $userInfo = $this->accountModel->school_user_login($schoolId, $username, $password);
            }
           
            if(!$userInfo || $userInfo['is_delete']) throw new Exception("请填写正确的账号密码");
            // 如果是老师，就顺便获取学校
            $userInfo['school'] = $schoolInfo = $this->schoolModel->get_school_info($userInfo['school_id']);
            if(!$schoolInfo || $schoolInfo['is_delete']) throw new Exception("请填写正确的账号密码");
            // 获取校区
            $params['schoolId'] = $schoolInfo['id'];
            $params['isDelete'] = 0;
            $campusList = $this->schoolModel->get_campus_list($params);
            $campusInfo = $campusList[0];
        }

        // 获取权限菜单。改动登录逻辑的话，需要连单点登录的代码也一起改
        $menuIdSet = false;
        // if($userInfo['user_type'] == USER_TYPE_SCHOOL) $menuIdSet = $schoolInfo['school_module_set'];
        // if($userInfo['user_type'] == USER_TYPE_TEACHER) $menuIdSet = $this->staffModel->get_menu_id_by_role_id($userInfo['role_id_set']);
        

        if($userInfo['user_type'] == USER_TYPE_SCHOOL) {
            $schoolMenuIdSet = $schoolInfo['school_module_set'];
            $menuIdSet = $schoolMenuIdSet;
        }

        if($userInfo['user_type'] == USER_TYPE_TEACHER) {
            $schoolMenuIdSet = $schoolInfo['school_module_set'];
            $userMenuIdSet = $this->staffModel->get_menu_id_by_role_id($userInfo['role_id_set']);
            $userMenuIdArr = explode(',', $userMenuIdSet);

            $schoolMenuIdArr = explode(',', $schoolMenuIdSet);
            // 获取菜单列表
            $menuList = $this->accountModel->get_admin_menu_all();
            // 按id
            $menuList = array_value_to_key($menuList, 'id');
                        // var_export($menuList);exit;
            // 判断是否在学校权限里
            foreach($userMenuIdArr as $key => $id) {
                if(isset($menuList[$id])) {
                    $parentId = $menuList[$id]['menu_pid'];
                } else {
                    $parentId = -1;
                }
                if(!in_array($id, $schoolMenuIdArr) && !in_array($parentId, $schoolMenuIdArr)) {
                    unset($userMenuIdArr[$key]);
                }
            }
            $menuIdSet = implode(',', $userMenuIdArr);
        }

        // 根据用户类型，获取后台菜单列表
        $roleData = $this->accountModel->get_admin_menu($userInfo['user_type'], $menuIdSet);
        $userInfo['roleMenu'] = $roleData['roleMenu'];
        $userInfo['roleArray'] = $roleData['roleArray'];

        // 改成执教关系
        if($userInfo['user_type'] == USER_TYPE_TEACHER) {
            // 获取班级列表
            $classParams['isDelete'] = 0;
            $classParams['schoolId'] = $userInfo['school_id'];
            $classList = $this->classesModel->get_class_list($classParams);
            // 使用id作为键
            $classList = array_value_to_key($classList, 'id');
            // 获取执教关系列表
            $coachParams['teacherId'] = $userInfo['id'];
            $coachList = $this->staffModel->get_coach_list($coachParams);
            // 通过coachList获取任课班级
            $userInfo['classIdArr'] = $this->getTeacherClassByCoachList($coachList, $userInfo['school_id'])['teacherClassIdArr'];
            $userInfo['classArr'] = $this->getTeacherClassByCoachList($coachList, $userInfo['school_id'])['teacherClassArr'];
            // 学校管理员classArr数据太长，存储session报错Failed to decode session object. Session has been destroyed
            // 将学校管理员的user_type设置为2，即为后台管理员
            if($this->checkIsSchoolAdminByCoachList($coachList)) {
                $userInfo['user_type'] = USER_TYPE_SCHOOL;
                $userInfo['classArr'] = array();
            }

            // var_export($userInfo['classArr']);exit;
            $userInfo['class_ids'] = count($userInfo['classIdArr']) > 0 ? implode(',', $userInfo['classIdArr']) : '-1';
        }

         // 头像
         if($userInfo['user_type'] == USER_TYPE_SUPER_ADMIN) {
            // 超管默认为男头像
            $userInfo['headimgurl'] = site_url(APPLICATION_FOLDER. "/views/") . ADMIN_DIR. "/" . "assets/images/man.jpg";
         } else {
            if(empty($userInfo['headimgurl'])) {
                if($userInfo['user_type'] == USER_TYPE_SCHOOL) {
                    // 管理员默认为男头像
                   $userInfo['headimgurl'] = site_url(APPLICATION_FOLDER. "/views/") . ADMIN_DIR. "/" . "assets/images/man.jpg";
                } else {
                   // 判断性别
                   if(isset($userInfo['gender']) && $userInfo['gender'] == '女') {
                       $userInfo['headimgurl'] = get_sys_img('woman.jpg');
                   } else {
                       $userInfo['headimgurl'] = site_url(APPLICATION_FOLDER. "/views/") . ADMIN_DIR. "/" . "assets/images/man.jpg";
                   }
                }
           }
         }

        // 去掉残存的单点登录module的session
        if($this->session->intensiveModule){
            $this->session->set_userdata("intensiveModule", NULL);
        }
        // 登录成功，数据写入session
        $this->session->set_userdata("rmxUser", $userInfo);
        $this->session->set_userdata("campusList", $campusList);
        $this->session->set_userdata("campusInfo", $campusInfo);
        // echo '<pre>';var_export($this->session->rmxUser);exit;
        exit(json("登录成功", true));
    }

    // 图像验证码
    public function captcha(){
    	//验证码
		$this->load->library('captcha');
		$code = $this->captcha->getCaptcha();

		// 添加验证码字符串到session
	  	$this->session->set_userdata("captcha", strtolower($code));
	  	$this->captcha->showImg();
    }
}
